package com.hskn.hss.module.rptCarWork.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hskn.hss.core.utils.LoginUtils;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.carTrack.mapper.CarTrackMapper;
import com.hskn.hss.module.jobset.entity.Jobset;
import com.hskn.hss.module.jobset.mapper.JobsetMapper;
import com.hskn.hss.module.rptCarWork.entity.RptCarWork;
import com.hskn.hss.module.rptCarWork.mapper.RptCarWorkMapper;
import com.hskn.hss.module.rptCarWork.service.RptCarWorkService;
import com.hskn.hss.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hskn
 * @since 2021-05-21
 */
@Service
public class RptCarWorkServiceImpl extends ServiceImpl<RptCarWorkMapper, RptCarWork> implements RptCarWorkService {

    @Resource
    private RptCarWorkMapper rptCarWorkMapper;
    @Resource
    private JobsetMapper jobsetMapper;


    @Override
    public JSONObject mList(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        JSONObject json = new JSONObject();
        QueryWrapper<RptCarWork> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByDesc(RptCarWork::getCreateTime);
//        机构  日期  状态  作业类型  车辆id
        String departmentId = params.getString("departmentId");
        if (StringUtils.isNotEmpty(departmentId)) {
            queryWrapper.lambda().eq(RptCarWork::getDepartmentId, departmentId);
        }
        String workDate = params.getString("workDate");
        if (StringUtils.isNotEmpty(workDate)) {
            queryWrapper.lambda().eq(RptCarWork::getWorkDate, workDate);
        }
        String workMonth = params.getString("workMonth");
        if (StringUtils.isNotEmpty(workMonth)) {
            queryWrapper.lambda().eq(RptCarWork::getWorkMonth, workMonth);
        }
        String planName = params.getString("planName");
        if (StringUtils.isNotEmpty(planName)) {
            queryWrapper.lambda().eq(RptCarWork::getPlanName, planName);
        }
        String status = params.getString("status");
        if (StringUtils.isNotEmpty(status)) {
            queryWrapper.lambda().eq(RptCarWork::getStatus, status);
        }
        String workType = params.getString("workType");
        if (StringUtils.isNotEmpty(workType)) {
            queryWrapper.lambda().eq(RptCarWork::getWorkType, workType);
        }
        String carId = params.getString("carId");
        if (StringUtils.isNotEmpty(carId)) {
            queryWrapper.lambda().eq(RptCarWork::getCarId, carId);
        }
        List<RptCarWork> list = rptCarWorkMapper.selectList(queryWrapper);
        for (RptCarWork rptCarWork : list) {
            if (null != rptCarWork.getStatus() && rptCarWork.getStatus() == 3) {
                rptCarWork.setFinishRate(new BigDecimal(100));
            } else {
                if (rptCarWork.getCompletePercent() >= 100) {
                    rptCarWork.setFinishRate(new BigDecimal(100));
                } else {
                    rptCarWork.setFinishRate(new BigDecimal(rptCarWork.getCompletePercent()));
                }
            }

        }
        json.put("list", list);
        return json;
    }

    @Override
    public JSONObject detailList(JSONObject params) throws HssException {
        JSONObject json = new JSONObject();

        //关联查询排班和网格
        List<RptCarWork> rptCarWorkList = rptCarWorkMapper.getJxqsWorkSceneList(params);
        //关联查询人员和车辆
        List<RptCarWork> jxzyWorkDetailList = rptCarWorkMapper.jxzyWorkDetail(params);
        List<RptCarWork> jxzyWorkDetailCollect = jxzyWorkDetailList.stream().filter(rptCarWork -> null != rptCarWork.getWorkType() && rptCarWork.getWorkType() == 2).collect(Collectors.toList());
        Jobset jobset = jobsetMapper.selectById("3");
        for (RptCarWork rptCarWork : rptCarWorkList) {
            if (null != rptCarWork.getWorkType()) {
                if (rptCarWork.getWorkType() == 2) {
                    List<RptCarWork> list1 = jxzyWorkDetailCollect.stream().filter(t -> t.getPlanId() != null && t.getPlanId().equals(rptCarWork.getPlanId())).collect(Collectors.toList());
                    List<RptCarWork> list2 = list1.stream().filter(t -> t.getShiftId().equals(rptCarWork.getShiftId())).collect(Collectors.toList());
                    int totalTangci = 0;
                    for (int i = 0; i < list2.size(); i++) {
                        RptCarWork t = list2.get(i);
                        // 把车推进去
                        // 单程距离
                        //总里程  除以 趟次  每趟里程 //2000
                        BigDecimal singleProgress = (t.getTangCi() == null || t.getTangCi() == 0) ? BigDecimal.ZERO : new BigDecimal(t.getAllProgress()).divide(new BigDecimal(t.getTangCi()), BigDecimal.ROUND_HALF_UP);
                        // 单程需完成距离
                        if (null != jobset) {
                            //每趟里程  乘以 里程完成率阀值 %  // 2000 * 0.7  1400
                            BigDecimal requireSingleProgress = new BigDecimal(jobset.getKmOkThreshold()).multiply(singleProgress).divide(new BigDecimal(100), BigDecimal.ROUND_HALF_UP);
                            // 现里程  除以    requireSingleProgress  得到完成了几趟  4000/1400

                            int thisTangci = (requireSingleProgress == null || requireSingleProgress.equals(BigDecimal.ZERO)) ? 0 : (null == t.getWorkMileage() ? BigDecimal.ZERO : t.getWorkMileage()).divide(requireSingleProgress, BigDecimal.ROUND_FLOOR).intValue();
                            if (null == rptCarWork.getTangCi()) {
                                rptCarWork.setTangCi(0);
                            }
                            if (thisTangci > rptCarWork.getTangCi()) {
                                thisTangci = rptCarWork.getTangCi();
                            }
                            t.setFinishTangci(thisTangci);
                            // 计算总完成趟次
                            totalTangci += thisTangci;
                        }
                    }
                    int rate = 0;
                    if (0 != rptCarWork.getTangCi()) {
                        rate = rptCarWork.getTangCi() == null || rptCarWork.getTangCi() == 0 ? 0 : totalTangci * 100 / rptCarWork.getTangCi();
                        if (rate >= 100) {

                            rate = 100;
                        }
                    }
                    rptCarWork.setFinishRate(new BigDecimal(rate));
                } else if (rptCarWork.getWorkType() == 3) {
                    if (null != rptCarWork.getStatus() && rptCarWork.getStatus() == 3) {
                        rptCarWork.setFinishRate(new BigDecimal(100));
                    } else {
                        if (rptCarWork.getCompletePercent() >= 100) {
                            rptCarWork.setFinishRate(new BigDecimal(100));
                        } else {
                            rptCarWork.setFinishRate(new BigDecimal(rptCarWork.getCompletePercent()));
                        }
                    }
                }
            }
        }
        rptCarWorkList = rptCarWorkList.stream().sorted(Comparator.comparing(RptCarWork::getFinishRate).reversed()).collect(Collectors.toList());
        json.put("list", rptCarWorkList);
        return json;
    }
}
